/*
 * @Author: xiehangyun 
 * @Date: 2025-05-16 10:34:07 
 * @Last Modified by: xiehangyun
 * @Last Modified time: 2025-05-16 22:50:34
 */

import { observable, configure } from "mobx";
import myImageApi from './MyImageApi'
import { ImageItem, ImageListResponse } from './MyImageApi'
configure({ enforceActions: "never" });

// 默认的图片列表数据
const defaultImages: ImageItem[] = [
    {
        id: '1',
        imageUrl: 'https://placekitten.com/300/300',
        name: '设计作品1',
        date: '2024-05-16'
    },
    {
        id: '2',
        imageUrl: 'https://placekitten.com/301/301',
        name: '设计作品2',
        date: '2024-05-15'
    },
    {
        id: '3',
        imageUrl: 'https://placekitten.com/302/302',
        name: '设计作品3',
        date: '2024-05-14'
    }
];

const myImageStore = observable({
    
    page: 1,//当前页面
    pageSize: 10,//分页数
    total: defaultImages.length,//总数
    list: defaultImages,//图片列表
    loading: false,//加载状态
    error: '',//错误信息
    
    //获取图片列表
    async getList(page: number = 1, pageSize: number = 10) {
        this.loading = true;
        this.page = page;
        this.pageSize = pageSize;
        try {
            const res = await myImageApi.getImageList({page, pageSize});
            this.list = res.data.list || defaultImages;
            this.total = res.data.total || defaultImages.length;
            this.error = '';
        } catch (err) {
            this.error = err.message || '获取图片列表失败';
            this.list = defaultImages;
            this.total = defaultImages.length;
        } finally {
            this.loading = false;
        }
    },
    
    //删除图片
    async delete(id: string) {
        this.loading = true;
        try {
            await myImageApi.deleteImage(id);
            this.error = '';
            await this.getList(this.page, this.pageSize);
        } catch (err) {
            this.error = err.message || '删除图片失败';
        } finally {
            this.loading = false;
        }
    },
    
    //上传图片
    async add(data: FormData) {
        this.loading = true;
        try {
            await myImageApi.uploadImage(data);
            this.error = '';
            await this.getList(1, this.pageSize); // 上传成功后返回第一页
        } catch (err) {
            this.error = err.message || '上传图片失败';
        } finally {
            this.loading = false;
        }
    }

}, {}, { deep: false });

export default myImageStore;